part of "../shelf.dart";

/// 是一种通用运算符，自动根据body的类型打包为合适的[Response]
/// 这样就可以传入任意我喜欢的body就可以了，达到简化服务端代码的目的
Response response(int statusCode, [dynamic body]) {
  // 根据data的类型，决定最终的header和body
  final Map<String, String> headers = {};
  late final String bodyStr;

  if (body == null) {
    // 如果没有数据，则返回空字符串
    headers[keyContentType] = valueText;
    bodyStr = "";
  } else if (isPrimitive(body)) {
    // 如果为原始值，则stringify后发送
    headers[keyContentType] = valueText;
    bodyStr = stringify(body);
  } else if (body is Json || body is JsonList || body is Jsonable) {
    // 如果是raw格式，则设置为json并且字符串化后发送
    // TODO：二进制可能也会被识别为这个，需要扩充
    headers[keyContentType] = valueJson;
    bodyStr = stringify(body);
  } else if (body is Exception || body is Bug) {
    // 如果是某种错误，则直接作为文字发送
    headers[keyContentType] = valueText;
    bodyStr = stringify(body);
  } else {
    throw Bug("类型${body.runtimeType}未编写编码方式，请修改代码");
  }

  // 将处理好的内容生成为Response
  return Response(statusCode, headers: headers, body: bodyStr);
}

Response responseOK([dynamic body]) => response(200, body);

const String keyContentType = "Content-Type";
const String valueText = "text/plain; charset=utf-8";
const String valueJson = "application/json; charset=utf-8";
